import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'

// 定义一个与路由兼容的菜单路由类型
interface MenuRoute {
  path: string
  component?: string | any
  name?: string
  redirect?: string
  meta?: {
    title?: string
    icon?: string
    hidden?: boolean
    [key: string]: any
  }
  children?: MenuRoute[]
}

/**
 * 菜单管理模块的Store
 */
export const useMenuStore = defineStore('menu', () => {
  // 从 localStorage 中恢复已保存的菜单路由
  const storedRoutes = localStorage.getItem('menu_routes');
  const initialRoutes = storedRoutes ? JSON.parse(storedRoutes) : [];
  
  // 动态路由 - 使用MenuRoute类型
  const routes = ref<MenuRoute[]>(initialRoutes);
  // 加载状态
  const loading = ref(false);

  /**
   * 设置路由并保存到localStorage
   * @param routeConfigs 路由配置
   */
  function setRoutes(routeConfigs: MenuRoute[] | any[]) {
    routes.value = routeConfigs as MenuRoute[];
    // 将菜单路由持久化保存到localStorage
    localStorage.setItem('menu_routes', JSON.stringify(routeConfigs));
    return routeConfigs;
  }

  /**
   * 重置状态
   */
  function resetState() {
    routes.value = [];
    // 同时清除localStorage中的菜单路由数据
    localStorage.removeItem('menu_routes');
  }

  return {
    routes,
    loading,
    setRoutes,
    resetState
  };
});
